import 'package:mobx/mobx.dart';
import '../models/team_model.dart';
import '../models/share_post_model.dart';
import '../models/video_model.dart';
import '../models/scan_result_model.dart';
import '../models/collection_model.dart';
import '../services/collection_service.dart';
import 'auth_store.dart';

part 'collection_store.g.dart';

class CollectionStore = _CollectionStore with _$CollectionStore;

abstract class _CollectionStore with Store {
  final CollectionService _collectionService = CollectionService();
  final AuthStore _authStore;

  _CollectionStore(this._authStore);

  @observable
  ObservableList<TeamModel> collectedTeams = ObservableList<TeamModel>();

  @observable
  ObservableList<SharePostModel> collectedShares =
      ObservableList<SharePostModel>();

  @observable
  ObservableList<VideoModel> collectedVideos = ObservableList<VideoModel>();

  @observable
  ObservableList<ScanResultModel> collectedScanResults =
      ObservableList<ScanResultModel>();

  @observable
  CollectionModel? userCollection;

  @observable
  bool isLoading = false;

  @observable
  String? errorMessage;

  @computed
  bool get hasCollections {
    return collectedTeams.isNotEmpty ||
        collectedShares.isNotEmpty ||
        collectedVideos.isNotEmpty ||
        collectedScanResults.isNotEmpty;
  }

  @action
  Future<void> loadUserCollections() async {
    if (_authStore.currentUser == null) return;

    isLoading = true;
    errorMessage = null;

    try {
      userCollection = await _collectionService.getOrCreateUserCollection(
        _authStore.currentUser!.id,
      );

      // 加载收藏的团队
      final teams = _collectionService.getUserCollectedTeams(
        _authStore.currentUser!.id,
      );
      collectedTeams.clear();
      collectedTeams.addAll(teams);

      // 加载收藏的分享
      final shares = _collectionService.getUserCollectedShares(
        _authStore.currentUser!.id,
      );
      collectedShares.clear();
      collectedShares.addAll(shares);

      // 加载收藏的视频
      final videos = _collectionService.getUserCollectedVideos(
        _authStore.currentUser!.id,
      );
      collectedVideos.clear();
      collectedVideos.addAll(videos);

      // 加载收藏的扫描结果
      final scanResults = _collectionService.getUserCollectedScanResults(
        _authStore.currentUser!.id,
      );
      collectedScanResults.clear();
      collectedScanResults.addAll(scanResults);

      isLoading = false;
    } catch (e) {
      errorMessage = 'Load collection failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  Future<void> toggleTeamCollection(String teamId) async {
    if (_authStore.currentUser == null) return;

    try {
      final userId = _authStore.currentUser!.id;
      final isCollected = _collectionService.isTeamCollected(userId, teamId);

      if (isCollected) {
        await _collectionService.removeTeamFromCollection(userId, teamId);
        collectedTeams.removeWhere((team) => team.id == teamId);
      } else {
        await _collectionService.addTeamToCollection(userId, teamId);

        // 重新加载团队以获取最新数据
        final teams = _collectionService.getUserCollectedTeams(userId);
        collectedTeams.clear();
        collectedTeams.addAll(teams);
      }
    } catch (e) {
      errorMessage = 'Update team collection status failed: ${e.toString()}';
    }
  }

  @action
  Future<void> toggleShareCollection(String shareId) async {
    if (_authStore.currentUser == null) return;

    try {
      final userId = _authStore.currentUser!.id;
      final isCollected = _collectionService.isShareCollected(userId, shareId);

      if (isCollected) {
        await _collectionService.removeShareFromCollection(userId, shareId);
        collectedShares.removeWhere((share) => share.id == shareId);
      } else {
        await _collectionService.addShareToCollection(userId, shareId);

        // 重新加载分享以获取最新数据
        final shares = _collectionService.getUserCollectedShares(userId);
        collectedShares.clear();
        collectedShares.addAll(shares);
      }
    } catch (e) {
      errorMessage = 'Update share collection status failed: ${e.toString()}';
    }
  }

  @action
  Future<void> toggleVideoCollection(String videoId) async {
    if (_authStore.currentUser == null) return;

    try {
      final userId = _authStore.currentUser!.id;
      final isCollected = _collectionService.isVideoCollected(userId, videoId);

      if (isCollected) {
        await _collectionService.removeVideoFromCollection(userId, videoId);
        collectedVideos.removeWhere((video) => video.id == videoId);
      } else {
        await _collectionService.addVideoToCollection(userId, videoId);

        // 重新加载视频以获取最新数据
        final videos = _collectionService.getUserCollectedVideos(userId);
        collectedVideos.clear();
        collectedVideos.addAll(videos);
      }
    } catch (e) {
      errorMessage = 'Update video collection status failed: ${e.toString()}';
    }
  }

  @action
  Future<void> toggleScanResultCollection(String scanResultId) async {
    if (_authStore.currentUser == null) return;

    try {
      final userId = _authStore.currentUser!.id;
      final isCollected = _collectionService.isScanResultCollected(
        userId,
        scanResultId,
      );

      if (isCollected) {
        await _collectionService.removeScanResultFromCollection(
          userId,
          scanResultId,
        );
        collectedScanResults.removeWhere((result) => result.id == scanResultId);
      } else {
        await _collectionService.addScanResultToCollection(
          userId,
          scanResultId,
        );

        // 重新加载扫描结果以获取最新数据
        final results = _collectionService.getUserCollectedScanResults(userId);
        collectedScanResults.clear();
        collectedScanResults.addAll(results);
      }
    } catch (e) {
      errorMessage =
          'Update scan result collection status failed: ${e.toString()}';
    }
  }

  @action
  bool isTeamInCollection(String teamId) {
    if (_authStore.currentUser == null) return false;
    return _collectionService.isTeamCollected(
      _authStore.currentUser!.id,
      teamId,
    );
  }

  @action
  bool isShareInCollection(String shareId) {
    if (_authStore.currentUser == null) return false;
    return _collectionService.isShareCollected(
      _authStore.currentUser!.id,
      shareId,
    );
  }

  @action
  bool isVideoInCollection(String videoId) {
    if (_authStore.currentUser == null) return false;
    return _collectionService.isVideoCollected(
      _authStore.currentUser!.id,
      videoId,
    );
  }

  @action
  bool isScanResultInCollection(String scanResultId) {
    if (_authStore.currentUser == null) return false;
    return _collectionService.isScanResultCollected(
      _authStore.currentUser!.id,
      scanResultId,
    );
  }
}
